package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.message.constant.QuotationPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.QuotationProductEntity;
import com.xbongbong.saas.domain.entity.QuotationUserEntity;
import com.xbongbong.saas.domain.entity.ext.QuotationEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.QuotationProductModel;
import com.xbongbong.saas.model.QuotationUserModel;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowQuotationStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private UserModel userModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private QuotationUserModel quotationUserModel;
    @Resource
    private QuotationProductModel quotationProductModel;
    @Resource
    private MessageService messageService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ProFormHelp proFormHelp;


    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.QUOTATION.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        User user = workflowTransferPOJO.getUser();
        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();

        Long newCustomerId = FastJsonHelper.getLongFromFormData(data, QuotationEnum.CUSTOMER_ID.getAttr());
        List<Long> newOpportunityIds = FastJsonHelper.getTransferTypesFromData(data, QuotationEnum.OPPORTUNITY_ID.getAttr(), Long.class);
        List<Long> newContactIds = FastJsonHelper.getTransferTypesFromData(data, QuotationEnum.CONTACT_ID.getAttr(), Long.class);

        try {
            // 新建更新客户最后联系时间
            Long lastConnectTime = DateTimeUtil.getInt();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), lastConnectTime);
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(newCustomerId, jsonObject, corpid);
            customerModel.updateBatch(Collections.singletonList(updateData), corpid);
        } catch (Exception e) {
            log.error("新建报价单更新客户最后联系时间", e);
        }

        PaasFormEntity paasForm = proFormHelp.getPaasForm(pojoData.getFormId(), pojoData.getBusinessType(), corpid);
        String paasFormName = ProjectLogEnum.QUOTATION_CREATE.getName();
        if (Objects.nonNull(paasForm)) {
            paasFormName = paasForm.getName();
        }

        //创建信息
        String creatorId = user.getUserId();
        UserEntity creatorUser = userModel.getByKeyIngoreDel(creatorId, corpid);
        //是否是第一次报价
        String version = data.getString(QuotationEnum.VERSION.getAttr());
        boolean isNotDistributeBusinessType = isNotDistributeBusinessType(workflowTransferPOJO);
        if (Objects.equals(version, StringConstant.DEFAULT_VERSION)) {
            try{
                //新建报价单
                String communicateMemo;
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                if(isNotDistributeBusinessType){
                     String memo = Objects.equals(workflowTransferPOJO.getIsImport(), 1) ? CrmLogMemoConstant.DYNAMIC_USER_IMPORT : CrmLogMemoConstant.DYNAMIC_USER_ADD;
                     communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUser.getName(), paasFormName, data.getString(BasicConstant.SERIAL_NO));
                }else {
                    String operate = Objects.equals(workflowTransferPOJO.getIsImport(), 1) ? I18nMessageUtil.getMessage(I18nStringConstant.IMPORTED) : I18nMessageUtil.getMessage(I18nStringConstant.ADD);
                    communicateMemo = creatorUser.getName() + operate + ProjectLogEnum.QUOTATION_CREATE.getName() + " :" + data.getString(BasicConstant.SERIAL_NO);
                    customerDynamicAddDTO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                }
                Integer subType = ProjectLogEnum.QUOTATION_CREATE.getSubType();
                String log = I18nMessageUtil.getMessage(I18nStringConstant.QUOTATION_ADD_LOG);
                String customerName = data.getString(QuotationEnum.CUSTOMER_NAME.getAttr());
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setCustomerId(newCustomerId);
                customerDynamicAddDTO.setContactIds(newContactIds);
                customerDynamicAddDTO.setOpportunityIds(newOpportunityIds);
                customerDynamicAddDTO.setCustomerName(customerName);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCommunicateBusinessText(data.getString(BasicConstant.SERIAL_NO));
                customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.QUOTATION.getCode());
                customerDynamicAddDTO.setDataId(dataId);
                customerDynamicAddDTO.setLogType(subType);
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }catch (Exception e){
                log.error("新建报价单", e);
            }
        } else {
            // 新版本，将上个版本的isNew置为0
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termQuery(QuotationEnum.getEsAttr4Keyword(QuotationEnum.IS_NEW), BasicConstant.ONE))
                    .filter(termQuery(QuotationEnum.getEsAttr4Keyword(QuotationEnum.GROUP_NUMBER), FastJsonHelper.getStringOrDefaultFromFormData(data, QuotationEnum.GROUP_NUMBER.getAttr(), "")))
                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())))
                    .filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_QUOTATION.getType()))
                    .mustNot(termQuery(FieldTypeEnum.DATAID.getAlias(), dataId));
            List<SortBuilder> sortBuilderList = new ArrayList<>();
            sortBuilderList.add(new FieldSortBuilder("addTime").order(SortOrder.DESC));
            List<QuotationEntityExt> quotationEntityExts = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_QUOTATION, filter, QuotationEntityExt.class, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()), sortBuilderList);
            if (!quotationEntityExts.isEmpty()) {
                QuotationEntityExt quotationEntityExt = quotationEntityExts.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(QuotationEnum.IS_NEW.getAttr(), 0);
                UpdateDataEntity updateData = ExplainUtil.getUpdateData(quotationEntityExt.getDataId(), jsonObject, corpid);
                quotationModel.updateBatch(Collections.singletonList(updateData), corpid);
            }

            try{
                //报价单新版本
                String communicateMemo;
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                if(isNotDistributeBusinessType){
                     String memo = Objects.equals(workflowTransferPOJO.getIsImport(), 1) ? CrmLogMemoConstant.DYNAMIC_USER_IMPORT_NEW_VERSION : CrmLogMemoConstant.DYNAMIC_USER_ADD_NEW_VERSION;
                     communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUser.getName(), paasFormName, data.getString(BasicConstant.SERIAL_NO));
                }else {
                    String operate = Objects.equals(workflowTransferPOJO.getIsImport(), 1) ? I18nMessageUtil.getMessage(I18nStringConstant.IMPORTED) : I18nMessageUtil.getMessage(I18nStringConstant.ADD);
                    communicateMemo = creatorUser.getName() + operate + ProjectLogEnum.QUOTATION_NEW_VERSION.getName() + " :" + data.getString(BasicConstant.SERIAL_NO);
                    customerDynamicAddDTO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                }
                Integer subType = ProjectLogEnum.QUOTATION_NEW_VERSION.getSubType();
                String log = I18nMessageUtil.getMessage(I18nStringConstant.QUOTATION_NEW_VERSION_LOG);

                String customerName = data.getString(QuotationEnum.CUSTOMER_NAME.getAttr());
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setCustomerId(newCustomerId);
                customerDynamicAddDTO.setContactIds(newContactIds);
                customerDynamicAddDTO.setOpportunityIds(newOpportunityIds);
                customerDynamicAddDTO.setCustomerName(customerName);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCommunicateBusinessText(data.getString(BasicConstant.SERIAL_NO));
                customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.QUOTATION.getCode());
                customerDynamicAddDTO.setDataId(dataId);
                customerDynamicAddDTO.setLogType(subType);
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }catch (Exception e){
                log.error("报价单新版本", e);
            }

            // 新版本操作日志
            String memoLog = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_NEW_VERSION), user.getName(), XbbRefTypeEnum.QUOTATION.getName(), data.getString(BasicConstant.SERIAL_NO));
            mongoLogHelp.buildLog(corpid, user.getUserId(), user.getName(), OperateModuleTypeEnum.QUOTATION, OperateTypeEnum.NEW_VERSION, dataId.toString(), data.getString(BasicConstant.SERIAL_NO), memoLog, null);
        }

        try {
            // 报价单创建消息推送
            QuotationEntityExt quotationEntityExt = new QuotationEntityExt();
            quotationEntityExt.setId(dataId);
            quotationEntityExt.setData(data);
            String serialNo = FastJsonHelper.getStringOrDefaultFromFormData(data, QuotationEnum.QUOTATION_NO.getAttr(), "");
            List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.QUOTATION_ADD_PUSH.getCode(), PushTypeEnum.QUOTATION_ADD_PUSH.getSubCode(), creatorUser, quotationEntityExt);
            PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_ADD_TITLE), String.format(I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_ADD_CONTENT), creatorUser.getName(), serialNo), null, options);
            messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.QUOTATION_ADD_PUSH);
        } catch (Exception e) {
            log.error("报价单创建消息推送", e);
        }


        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        //log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);


        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();

        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
        JSONObject oldData = workflowBackupDataEntity.getData();

        try {
            // 报价状态变更消息推送
            String oldStatus = FastJsonHelper.getStringOrDefaultFromFormData(oldData, QuotationEnum.STATUS.getAttr(), "");
            String newStatus = FastJsonHelper.getStringOrDefaultFromFormData(data, QuotationEnum.STATUS.getAttr(), "");
            String name = FastJsonHelper.getStringOrDefaultFromFormData(data, QuotationEnum.NAME.getAttr(), "");
            if (!Objects.equals(oldStatus, newStatus)) {
                PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(pojoData.getFormId(), corpid);
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
                if (Objects.isNull(explainMap)) {
                    PaasFormExplainEntity byBusinessType = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.QUOTATION.getCode(), corpid);
                    explainMap = ExplainUtil.getExplainMapByAttr(byBusinessType.getExplains(), QuotationEnum.STATUS.getAttr());
                }
                FieldAttrEntity statusAttrEntity = explainMap.get(QuotationEnum.STATUS.getAttr());
                if (Objects.nonNull(statusAttrEntity)) {
                    List<ItemPoJo> items = statusAttrEntity.getItems();
                    for (ItemPoJo itemPoJo: items) {
                        if (Objects.equals(itemPoJo.getValue(), newStatus)) {
                            newStatus = itemPoJo.getText();
                        }
                    }
                }

                UserEntity userEntity = userModel.getByKeyIngoreDel(user.getUserId(), corpid);
                QuotationEntityExt quotationEntity = new QuotationEntityExt();
                quotationEntity.setId(dataId);
                quotationEntity.setData(data);
                List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.QUOTATION_STATUS_PUSH.getCode(), PushTypeEnum.QUOTATION_STATUS_PUSH.getSubCode(), userEntity, quotationEntity);
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(quotationEntity.getAppId(), quotationEntity.getMenuId(), quotationEntity.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
                MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_CHANGE_TITLE), String.format(I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_CHANGE_CONTENT), user.getName(), name, newStatus), null, options);
                messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.QUOTATION_STATUS_PUSH);
            }
        } catch (Exception e) {
            log.error("报价单保存时报价状态变更消息推送", e);
        }


        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                QuotationEntityExt quotationEntityExt = new QuotationEntityExt();
                quotationEntityExt.setId(dataId);
                quotationEntityExt.setCorpid(corpid);
                quotationEntityExt.setData(data);
                quotationEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                quotationEntityExt.setOwnerId(getOwnerId(data));
                quotationEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                List<QuotationUserEntity> contractUserList = JSON.parseArray(data.getString(StringConstant.USER_TEAM), QuotationUserEntity.class);

                List<QuotationProductEntity> productList = JSON.parseArray(data.getString(StringConstant.PRODUCT), QuotationProductEntity.class);

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                data.remove(StringConstant.PRODUCT);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    quotationEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                quotationModel.update(quotationEntityExt);
                // 回退被删掉的子表单
                updateBackSubForm(quotationEntityExt, corpid, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
                saveUserTeam(contractUserList, corpid, quotationEntityExt.getId());
                saveProduct(productList, corpid, quotationEntityExt.getId());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowQuotationStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            QuotationEntityExt purchaseEntityExt = new QuotationEntityExt();
            purchaseEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                purchaseEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                purchaseEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            purchaseEntityExt.setCorpid(corpid);
            purchaseEntityExt.setUpdateTime(DateTimeUtil.getInt());
            quotationModel.update(purchaseEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_QUOTATION_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 关联产品
            List<QuotationProductEntity> productList = quotationProductModel.getProductsByQuoId( dataId, corpid);
            if (CollectionsUtil.isNotEmpty(productList)) {
                List<Long> idIn = new ArrayList<>();
                productList.forEach(item->idIn.add(item.getId()));
                quotationProductModel.deleteBatch(idIn, corpid, del.getDel());
            }
            // 团队
            List<QuotationUserEntity> contractUserList = quotationUserModel.getQuotationUserList(corpid, dataId, null);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                quotationUserModel.deleteBatchUser(contractUserList, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowQuotationStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveProduct(List<QuotationProductEntity> list, String corpid, Long dataId) throws XbbException {
        try {
            List<QuotationProductEntity> productList = quotationProductModel.getProductsByQuoId(dataId, corpid);

            // 遍历数据库中的产品
            List<Long> deleteList = new ArrayList<>();

            // 遍历备份表中的产品
            List<Long> backupProductId = new ArrayList<>();
            list.forEach(item->backupProductId.add(item.getId()));


            // 移除掉备份表中的产品
            productList.forEach(item->{
                if (!backupProductId.contains(item.getId())) {
                    deleteList.add(item.getId());
                }
            });

            if (CollectionsUtil.isNotEmpty(deleteList)) {
                quotationProductModel.deleteBatch(deleteList, corpid, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                quotationProductModel.updateBatch(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowQuotationStrategy.saveProduct error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
    /**
     * 保存团队
     * @param list
     * @param corpid
     * @param dataId
     * @throws XbbException
     */
    private void saveUserTeam(List<QuotationUserEntity> list, String corpid, Long dataId) throws XbbException {

        try {
            List<QuotationUserEntity> contractUserList = quotationUserModel.getQuotationUserList(corpid, dataId, null);
            List<Long> idList = new ArrayList<>();
            list.forEach(item->idList.add(item.getId()));

            contractUserList.removeIf(item->idList.contains(item.getId()));
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                quotationUserModel.deleteBatchUser(contractUserList, corpid, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                quotationUserModel.updateBatch(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowQuotationStrategy.saveUserTeam error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
